/*
 * THE SOURCE CODES OF THE SOFTWARE ARE VALUABLE ASSETS OF FIDUS TECHNOLOGIES LTD.
 * YOU AGREE TO KEEP ALL SOURCE CODES OF THE SOFTWARE IN CONFIDENCE. YOU MAY NOT TRANSFER
 * OR ASSIGN THE SOFTWARE OR YOUR RIGHTS UNDER THIS AGREEMENT.
 * LIMITED WARRANTY
 * THE SOFTWARE AND ACCOMPANYING WRITTEN MATERIALS (INCLUDING INSTRUCTIONS FOR USE) ARE PROVIDED "AS IS"
 * AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. YOU ASSUME THE ENTIRE
 * RISK AS TO THE RESULTS AND PERFORMANCE OF THE SOFTWARE.
 * FIDUS TECHNOLOGIES DOES NOT WARRANT THAT THE SOFTWARE WILL MEET ALL YOUR REQUIREMENTS, THAT OPERATIONS
 * OF THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT ALL SOFTWARE ERRORS WILL BE CORRECTED.
 * FIDUS TECHNOLOGIES-SOFTWARE SOLUTIONS IS NOT RESPONSIBLE FOR PROBLEMS CAUSED BY CHANGES IN THE
 * OPERATING CHARACTERISTICS OF COMPUTER HARDWARE OR COMPUTER OPERATING SYSTEMS WHICH ARE MADE AFTER
 * WHICH ARE MADE AFTER THE RELEASE OF THE SOFTWARE NOR FOR PROBLEMS IN THE INTERACTION OF THE SOFTWARE
 * WITH NON-FIDUS TECHNOLOGIES APPLICATION.WILL HAVE NO RESPONSIBILITY TO REPLACE OR REFUND THE LICENSE FEES
 * FOR MEDIA DAMAGED BY ACCIDENT, ABUSE OR MISAPPLICATION. THIS SOFTWARE IS INTENDED FOR COMMERCIAL,
 * INSTITUTIONAL, AND INDUSTRIAL USERS. THE ABOVE WARRANTIES ARE EXCLUSIVE AND IN LIEU OF ALL OTHER WARRANTIES,
 * WHETHER EXPRESSED OR IMPLIED, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NON-INFRINGEMENT. NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY FIDUS TECHNOLOGIES,
 * ITS EMPLOYEES, DISTRIBUTORS, DEALERS OR AGENTS SHALL INCREASE THE SCOPE OF THE ABOVE WARRANTIES OR
 * CREATE ANY NEW WARRANTIES. NEITHER FIDUS TECHNOLOGIES NOR ANYONE ELSE WHO HAS BEEN INVOLVED IN THE
 * CREATION, PRODUCTION OR DELIVERY OF THE SOFTWARE SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES (INCLUDING DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS LOSSES, BUSINESS
 * INTERRUPTION, LOSS OF DATA, AND THE LIKE) ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE,
 * OR ANY OTHER CLAIM BY ANY PARTY EVEN IF FIDUS TECHNOLOGIES HAS BEEN ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGES. IN THE EVENT FIDUS TECHNOLOGIES IS LIABLE FOR ANY DAMAGES, FIDUS TECHNOLOGIES' LIABILITY
 * FOR DAMAGES SHALL BE LIMITED TO THE AMOUNT PAID FOR THE SOFTWARE UNDER THE TERMS AND CONDITIONS OF THIS
 * AGREEMENT.
 * http://www.fidustechnologies.com
 * Copyright(C) 2010 FIDUS TECHNOLOGIES-Software Solutions(R)
 * All rights reserved.
 */

/*
 * ItemDetailsView.java
 *
 * Created on 3 Sep, 2010, 1:46:51 PM
 */

package com.fidus.inventory.UI.Items;

import com.fidus.inventory.UI.CallableComponent;
import com.fidus.inventory.beans.items.ItemDetails;
import com.fidus.inventory.beans.items.ItemStock;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JOptionPane;
import oracle.toplink.essentials.expressions.Expression;
import oracle.toplink.essentials.expressions.ExpressionBuilder;
import org.jdesktop.application.Action;
import org.jdesktop.beansbinding.AbstractBindingListener;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.PropertyStateEvent;

/**
 *
 * @author Mahesh Kedari<mahesh.kedari@fidustechnologies.com>
 */
public class ItemDetailsView extends javax.swing.JPanel implements CallableComponent{
    private static String dockable_ID;
    /** Creates new form ItemDetailsView */
    public ItemDetailsView() {
        initComponents();
        entityManager.getTransaction().begin();
        bindingGroup.addBindingListener(new AbstractBindingListener() {
            @Override
            public void targetChanged(Binding binding, PropertyStateEvent event) {
                setSaveNeeded(true);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("inventorymanagement_dbPU").createEntityManager();
        itemStockQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT i FROM ItemStock i");
        itemStockList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(itemStockQuery.getResultList());
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(simple_inventory.Simple_InventoryApp.class).getContext().getResourceMap(ItemDetailsView.class);
        itemDetailsQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("itemDetailsQuery.query")); // NOI18N
        itemDetailsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : itemDetailsQuery.getResultList();
        measurementUnitConverter1 = new com.fidus.inventory.UI.Items.MeasurementUnitConverter();
        titleLabel = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        itemCodeLabel = new javax.swing.JLabel();
        measureUnitLabel = new javax.swing.JLabel();
        descriptionLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        itemCodeTextField = new javax.swing.JTextField();
        itemNameTextField = new javax.swing.JTextField();
        unitComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        descriptionTextArea = new javax.swing.JTextArea();
        jToolBar1 = new javax.swing.JToolBar();
        newButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jXTable1 = new org.jdesktop.swingx.JXTable();
        itemNameLabel = new javax.swing.JLabel();

        setName("Form"); // NOI18N

        titleLabel.setFont(resourceMap.getFont("titleLabel.font")); // NOI18N
        titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        titleLabel.setText(resourceMap.getString("titleLabel.text")); // NOI18N
        titleLabel.setName("titleLabel"); // NOI18N

        jSeparator1.setName("jSeparator1"); // NOI18N

        itemCodeLabel.setLabelFor(itemCodeTextField);
        itemCodeLabel.setText(resourceMap.getString("itemCodeLabel.text")); // NOI18N
        itemCodeLabel.setName("itemCodeLabel"); // NOI18N

        measureUnitLabel.setLabelFor(unitComboBox);
        measureUnitLabel.setText(resourceMap.getString("measureUnitLabel.text")); // NOI18N
        measureUnitLabel.setName("measureUnitLabel"); // NOI18N

        descriptionLabel.setLabelFor(descriptionTextArea);
        descriptionLabel.setText(resourceMap.getString("descriptionLabel.text")); // NOI18N
        descriptionLabel.setName("descriptionLabel"); // NOI18N

        jLabel5.setName("jLabel5"); // NOI18N

        itemCodeTextField.setName("itemCodeTextField"); // NOI18N

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedItem.itemCode}"), itemCodeTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validItem}"), itemCodeTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        itemNameTextField.setName("itemNameTextField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedItem.itemName}"), itemNameTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validItem}"), itemNameTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        unitComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "KG", "Ltrs", "milligram", "millileters", "Mtrs", "CenteMtrs" }));
        unitComboBox.setName("unitComboBox"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedItem.measurementUnit}"), unitComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        binding.setConverter(measurementUnitConverter1);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validItem}"), unitComboBox, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        descriptionTextArea.setColumns(17);
        descriptionTextArea.setRows(2);
        descriptionTextArea.setTabSize(1);
        descriptionTextArea.setName("descriptionTextArea"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedItem.description}"), descriptionTextArea, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validItem}"), descriptionTextArea, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jScrollPane1.setViewportView(descriptionTextArea);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(simple_inventory.Simple_InventoryApp.class).getContext().getActionMap(ItemDetailsView.class, this);
        newButton.setAction(actionMap.get("newItem")); // NOI18N
        newButton.setText(resourceMap.getString("newButton.text")); // NOI18N
        newButton.setFocusable(false);
        newButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newButton.setName("newButton"); // NOI18N
        newButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(newButton);

        saveButton.setAction(actionMap.get("saveRecord")); // NOI18N
        saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
        saveButton.setFocusable(false);
        saveButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        saveButton.setName("saveButton"); // NOI18N
        saveButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(saveButton);

        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setFocusable(false);
        deleteButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        deleteButton.setName("deleteButton"); // NOI18N
        deleteButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(deleteButton);

        refreshButton.setText(resourceMap.getString("refreshButton.text")); // NOI18N
        refreshButton.setFocusable(false);
        refreshButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        refreshButton.setName("refreshButton"); // NOI18N
        refreshButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(refreshButton);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jXTable1.setToolTipText(resourceMap.getString("jXTable1.toolTipText")); // NOI18N
        jXTable1.setColumnSelectionAllowed(true);
        jXTable1.setName("jXTable1"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, itemStockList, jXTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stockQuantity}"));
        columnBinding.setColumnName("Stock Quantity");
        columnBinding.setColumnClass(Float.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastCheckedOn}"));
        columnBinding.setColumnName("Last Checked On");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastPurchasedQuantity}"));
        columnBinding.setColumnName("Last Purchased Quantity");
        columnBinding.setColumnClass(Float.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${itempurchase.purchaseDate}"));
        columnBinding.setColumnName("Date");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane2.setViewportView(jXTable1);
        jXTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jXTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jXTable1.columnModel.title0")); // NOI18N
        jXTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jXTable1.columnModel.title1")); // NOI18N
        jXTable1.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jXTable1.columnModel.title2")); // NOI18N

        itemNameLabel.setLabelFor(itemNameTextField);
        itemNameLabel.setText(resourceMap.getString("itemNameLabel.text")); // NOI18N
        itemNameLabel.setName("itemNameLabel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(titleLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 710, Short.MAX_VALUE)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 710, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(itemCodeLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addComponent(descriptionLabel))
                            .addGap(26, 26, 26))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(measureUnitLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(itemNameLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(itemNameTextField, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(itemCodeTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
                    .addComponent(unitComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE))
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 710, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(itemCodeLabel)
                            .addComponent(itemCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(itemNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(itemNameLabel))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(unitComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(measureUnitLabel))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(descriptionLabel))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(31, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE)))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton deleteButton;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JTextArea descriptionTextArea;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JLabel itemCodeLabel;
    private javax.swing.JTextField itemCodeTextField;
    private java.util.List itemDetailsList;
    private javax.persistence.Query itemDetailsQuery;
    private javax.swing.JLabel itemNameLabel;
    private javax.swing.JTextField itemNameTextField;
    private java.util.List<com.fidus.inventory.beans.items.ItemStock> itemStockList;
    private javax.persistence.Query itemStockQuery;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private org.jdesktop.swingx.JXTable jXTable1;
    private javax.swing.JLabel measureUnitLabel;
    private com.fidus.inventory.UI.Items.MeasurementUnitConverter measurementUnitConverter1;
    private javax.swing.JButton newButton;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel titleLabel;
    private javax.swing.JComboBox unitComboBox;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private ExpressionBuilder stockExpressionBuilder = new ExpressionBuilder(ItemStock.class);
    
    //<editor-fold defaultstate="collapsed" desc="Handle selected Item">
    protected boolean validItem;
    public static final String PROP_VALIDITEM = "validItem";

    /**
     * Get the value of validItem
     *
     * @return the value of validItem
     */
    public boolean isValidItem() {
        return selectedItem!=null;
    }

    /**
     * Set the value of validItem
     *
     * @param validItem new value of validItem
     */
    public void setValidItem(boolean validItem) {
        boolean oldValidItem = this.validItem;
        this.validItem = validItem;
        propertyChangeSupport.firePropertyChange(PROP_VALIDITEM, oldValidItem, validItem);
    }

    protected ItemDetails selectedItem;
    public static final String PROP_SELECTEDITEM = "selectedItem";

    /**
     * selectedItem is the object used in this form for processing
     *
     * @return ItemDetails type object selectedItem
     */
    public ItemDetails getSelectedItem() {
        return selectedItem;
    }

    /**
     * Set new value of selectedItem
     *
     * @param new value for selectedItem of ItemDetails type
     */
    public void setSelectedItem(ItemDetails selectedItem) {
        ItemDetails oldSelectedItem = this.selectedItem;
        this.selectedItem = selectedItem;
        propertyChangeSupport.firePropertyChange(PROP_SELECTEDITEM, oldSelectedItem, selectedItem);
        // Load Table data
        loadTableData(selectedItem);
        setValidItem(true);
    }

    /*
     * load new data to table when selected Item is changed
     */
    private void loadTableData(ItemDetails selectedItem) {
        if(selectedItem.getItemID()==null){
            return;
        }
        itemStockList.removeAll(itemStockList);
        if(isValidItem()){
            Expression expression = stockExpressionBuilder.get("itemDetails").equal(selectedItem);
            List<ItemStock> tempStockList = ((oracle.toplink.essentials.ejb.cmp3.EntityManager)
                    entityManager.getDelegate()).createQuery(expression, ItemStock.class).getResultList();
            itemStockList.addAll(tempStockList);
        }
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Tool bar buttons action">
    /**
     * This action will handle creation of new Item record
     */
    @Action
    public void newItem(){
        // Check if form contains any unsaved data
        if(isSaveNeeded()){
            int choice = JOptionPane.showConfirmDialog(null, "<HTML>Unsaved Record Found. This Action will<br/>"
                    + "delete any unsaved record available in form<br/> Do you want to continue?", "Item Details",
                    JOptionPane.YES_NO_OPTION);
            if(choice== JOptionPane.NO_OPTION){
                // If user does not want to loose unsaved data, return from function
                return;
            }
        }
        // Create new ItemDetails object add it to itemDetailsList
        ItemDetails newItemDetails = new ItemDetails();
        itemDetailsList.add(newItemDetails);
        //Inform entityManager about presence of new object
        entityManager.persist(newItemDetails);
        setSelectedItem(newItemDetails);
    }

    protected boolean saveNeeded;
    /**
     * This property will enable/disable save button as per the transaction
     * status
     */
    public static final String PROP_SAVENEEDED = "saveNeeded";

    /**
     * Get the value of saveNeeded
     *
     * @return true: If any data in form is changed and details are not
     *               committed in database
     *         false: No uncommitted changes in form
     */
    public boolean isSaveNeeded() {
        return saveNeeded;
    }

    /**
     * Set the value of saveNeeded
     *
     * @param saveNeeded new value of saveNeeded
     */
    public void setSaveNeeded(boolean saveNeeded) {
        boolean oldSaveNeeded = this.saveNeeded;
        this.saveNeeded = saveNeeded;
        propertyChangeSupport.firePropertyChange(PROP_SAVENEEDED, oldSaveNeeded, saveNeeded);
    }

        @Action(enabledProperty="saveNeeded")
    public void saveRecord(){
        try {
            entityManager.getTransaction().commit();
            JOptionPane.showMessageDialog(null, "Record Saved Successfully", "Item Details", JOptionPane.PLAIN_MESSAGE);
            setSaveNeeded(false);
        } catch (RollbackException ex) {
            JOptionPane.showMessageDialog(null, "Failed to save record", "Item Details", JOptionPane.ERROR_MESSAGE);
            //TODO handle Rollback exception
        } finally {
            /* If transaction is not active, begin new transaction */
            if(!entityManager.getTransaction().isActive()){
                entityManager.getTransaction().begin();
            }
        }
    }

    @Action(enabledProperty=PROP_VALIDITEM)
    public void deleteRecord(){
        // Ask user for confirmation on record deletion
        int choice = JOptionPane.showConfirmDialog(null, "<HTML>Are you sure you want to <br/>"
                + "delete this item?</HTML>", "Item Details", JOptionPane.YES_NO_OPTION);
        if(choice==JOptionPane.NO_OPTION){
            // If user choice is NO, return from this function
            return;
        }
        // If user choice is YES, execute below code
        itemDetailsList.remove(selectedItem);
        entityManager.remove(selectedItem);
        setSelectedItem(null);
        propertyChangeSupport.firePropertyChange(PROP_VALIDITEM, isValidItem(), false);
        setSaveNeeded(true);
    }

    @Action(enabledProperty=PROP_VALIDITEM)
    public void clearForm(){
        
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Property Change Support">
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    /**
     * Add PropertyChangeListener.
     *
     * @param listener
     */
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    /**
     * Remove PropertyChangeListener.
     *
     * @param listener
     */
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

    //</editor-fold>

    public void callingMethod(Object... object) {
        if(object[0] instanceof ItemDetails){
            setSelectedItem((ItemDetails)object[0]);
        }
    }

    public Object getDockedObject() {
        return this;
    }

    public String getDockedID() {
        return dockable_ID;
    }
    public void setDockedID(String dockable_ID){
        ItemDetailsView.dockable_ID = dockable_ID;
    }



}
